package com.pocketsweet.ui.uilib.adapter;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.pocketsweet.MLApplication;
import com.pocketsweet.R;
import com.pocketsweet.chatlib.utils.PicassoSquare;
import com.pocketsweet.ui.Profile;
import com.pocketsweet.utils.SortModel;
import com.pocketsweet.utils.StringUtils;
import com.squareup.picasso.Picasso;

public class SortAdapter extends BaseAdapter implements SectionIndexer {
	private List<SortModel> list = null;
	private Context mContext;

	public SortAdapter(Context mContext) {
		this.mContext = mContext;
	}

	public SortAdapter(Context mContext, List<SortModel> list) {
		this.mContext = mContext;
		this.list = list;
	}

	/**
	 * 当ListView数据发生变化时,调用此方法来更新ListView
	 * 
	 * @param list
	 */
	public void updateListView(List<SortModel> list) {
		this.list = list;
		notifyDataSetChanged();
	}

	public int getCount() {
		return this.list.size();
	}

	public Object getItem(int position) {
		return list.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		final SortModel mContent = list.get(position);
		ViewHolder viewHolder = null;
		String location = null;
		if (convertView == null) {
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.item_friend_listview, parent, false);
			viewHolder = new ViewHolder(convertView);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		viewHolder.refreshView(this.list.get(position), position);
		return convertView;

	}

	private class ViewHolder implements View.OnClickListener {
		TextView catalog;
		ImageView imgAvatar;
		TextView tvuserName;
		SortModel sortModel;
		private View parent;
		private String nickname;

		ViewHolder(View parent) {
			this.parent = parent;
			initView(parent);
		}

		private void initView(View parent2) {
			this.catalog = (TextView) parent.findViewById(R.id.catalog);
			this.imgAvatar = (ImageView) parent.findViewById(R.id.imgAvatar);
			this.tvuserName = (TextView) parent.findViewById(R.id.tvuserName);
		}

		public void refreshView(SortModel sortModel1, int position) {
			this.sortModel = sortModel1;
			String location = null;
			// 根据position获取分类的首字母的Char ascii值
			int section = getSectionForPosition(position);

			// 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
			if (position == getPositionForSection(section)) {
				catalog.setVisibility(View.VISIBLE);
				if (sortModel.getSortLetters().equals("☆")) {
					catalog.setText("口袋恋人");
				} else {
					catalog.setText(sortModel.getSortLetters());
				}
			} else {
				catalog.setVisibility(View.GONE);
			}
			JSONObject user = sortModel.getUser();
			try {
				String avatar = user.getString("subAvatar");
				if (!StringUtils.isEmpty(avatar)) {
					Picasso.with(MLApplication.getContext()).load(avatar)
							.placeholder(R.drawable.default_avatar)
							.transform(new PicassoSquare()).into(imgAvatar);
				}
				// 设置姓名
				nickname = user.getString("nickname");
				tvuserName.setText(nickname);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			imgAvatar.setOnClickListener(this);

		}

		@Override
		public void onClick(View v) {
			try {
				String selectedUserId = sortModel.getUser().getString(
						"objectId");
				Intent intent = new Intent(mContext, Profile.class);
				intent.putExtra("userId", selectedUserId);
				intent.putExtra("nickname", nickname);
				mContext.startActivity(intent);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * 根据ListView的当前位置获取分类的首字母的Char ascii值
	 */
	public int getSectionForPosition(int position) {
		return list.get(position).getSortLetters().charAt(0);
	}

	/**
	 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < getCount(); i++) {
			String sortStr = list.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}

		return -1;
	}

	/**
	 * 提取英文的首字母，非英文字母用#代替。
	 * 
	 * @param str
	 * @return
	 */
	private String getAlpha(String str) {
		String sortStr = str.trim().substring(0, 1).toUpperCase();
		// 正则表达式，判断首字母是否是英文字母
		if (sortStr.matches("[A-Z]")) {
			return sortStr;
		} else {
			return "#";
		}
	}

	@Override
	public Object[] getSections() {
		return null;
	}
}